package chat;


import java.io.*;
import java.net.Socket;

/**
 * @Author GongXl
 * @Description 不断的循环监听客户端的数据，每次都会阻塞
 * @Date 031 16:28
 * @Param
 * @return
**/
public class ThreadServer implements Runnable {
    private Socket socket;
    public ThreadServer(Socket socket){
        this.socket =  socket;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//迭代列表中所有socket
//            for (int i = 0; i < SrverTest.socketspool.size(); i++) {
                try {
                    BufferedReader is = new BufferedReader(new InputStreamReader(
                            socket.getInputStream()));
                    String readline = is.readLine();
                    System.out.println(socket+"说："+readline);
                    //TODO 告诉所有的客户端，xxx说了什么
                    boardCastAllClient(socket.getInetAddress().getHostAddress()+":"+socket.getPort(),readline);
                } catch (Exception e) {
                    e.printStackTrace();
                    removeClient(socket.getInetAddress().getHostAddress()+":"+socket.getPort());
                }
//            }
        }
    }
    /**
     * @Author GongXl
     * @Description 广播给所有的客户端信息
     * @Date 001 10:29
     * @Param []
     * @return void
    **/
    public void boardCastAllClient(String sayClinetIpPort,String readline) throws IOException {
        for (int i = 0; i < SrverTest.socketspool.size(); i++) {
            Socket socket = SrverTest.socketspool.get(i);
            String otherIpPort = socket.getInetAddress().getHostAddress()+":"+socket.getPort();
            //给不是自己的其他客户发消息
            if(!sayClinetIpPort.equals(otherIpPort)){
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                        socket.getOutputStream()));
                bw.write(readline);//发送信息给客户端
                bw.flush();
                System.out.println("已经广播给->"+socket);
//                bw.close();
            }
        }
    }
    /**
     * @Author GongXl
     * @Description 移除断掉的socket
     * @Date 001 10:43
     * @Param [ip]
     * @return void
    **/
    public void removeClient(String ipPort){
        for (int i = 0; i < SrverTest.socketspool.size(); i++) {
            Socket socket = SrverTest.socketspool.get(i);
            String otherIpPort = socket.getInetAddress().getHostAddress() + ":" +socket.getPort();
            //给不是自己的其他客户发消息
            if(ipPort.equals(otherIpPort)){
                SrverTest.socketspool.remove(i);
            }
        }
    }
    public static void main(String[] args) {

    }
}